package com.flyco.modules.stm.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.flyco.common.constant.StockConstant;
import com.flyco.modules.pms.entity.PmsProduct;
import com.flyco.modules.pms.service.IPmsProductService;
import com.flyco.modules.stm.entity.*;
import com.flyco.modules.stm.model.StmTransferItemModel;
import com.flyco.modules.stm.service.*;
import com.flyco.modules.stm.vo.StmPrintVO;
import com.flyco.modules.stm.vo.StmStockVO;
import org.apache.shiro.SecurityUtils;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.stm.vo.StmTransferPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.flyco.common.aspect.annotation.AutoLog;

/**
 * @Description: 门店调拨单
 * @Author: flyco
 * @Date: 2020-10-30
 * @Version: V1.0
 */
@Api(tags = "门店调拨单")
@RestController
@RequestMapping("/f/stm/stmTransfer")
@Slf4j
public class StmTransferController {
    @Autowired
    private IStmTransferService stmTransferService;
    @Autowired
    private IStmTransferItemService stmTransferItemService;
    @Autowired
    private IStmStoreInfoService stmStoreInfoService;
    @Autowired
    private IPmsProductService pmsProductService;
    @Autowired
    private IStmStockService stmStockService;
    @Autowired
    private IStmReplenishmentService stmReplenishmentService;
    @Autowired
    private IStmReplenishmentTransferRelationService stmReplenishmentTransferRelationService;
    @Autowired
    private IStmSalesService stmSalesService;

    /**
     * 分页列表查询
     *
     * @param stmTransfer
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "门店调拨单-分页列表查询")
    @ApiOperation(value = "门店调拨单-分页列表查询", notes = "门店调拨单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(StmTransfer stmTransfer,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<StmTransfer> queryWrapper = QueryGenerator.initQueryWrapper(stmTransfer, req.getParameterMap());
        Page<StmTransfer> page = new Page<StmTransfer>(pageNo, pageSize);
        IPage<StmTransfer> pageList = stmTransferService.page(page, queryWrapper);
        if (pageList.getTotal() > 0) {
            List<StmSales> salesList = stmSalesService.list();
            Map<Long, String> salesMap = salesList.stream().collect(Collectors.toMap(StmSales::getId, StmSales::getName, (key1, key2) -> key2));
            List<StmStoreInfo> storeInfos = stmStoreInfoService.list();
            Map<Long, String> storeInfoMaps = storeInfos.stream().collect(Collectors.toMap(StmStoreInfo::getStoreId, StmStoreInfo::getName, (key1, key2) -> key2));
            pageList.getRecords().forEach(transfer -> {
                if (oConvertUtils.isNotEmpty(transfer.getInStoreId())) {
                    if (storeInfoMaps.containsKey(transfer.getInStoreId())) {
                        transfer.setInStoreId_dictText(storeInfoMaps.get(transfer.getInStoreId()));
                    } else {
                        if (Objects.equals(0L , transfer.getInStoreId() )) {
                            transfer.setInStoreId_dictText("线上商城");
                        }
                    }
                }
                if (oConvertUtils.isNotEmpty(transfer.getOutStoreId())) {
                    if (storeInfoMaps.containsKey(transfer.getOutStoreId())) {
                        transfer.setOutStoreId_dictText(storeInfoMaps.get(transfer.getOutStoreId()));
                    } else {
                        if (Objects.equals(0L , transfer.getOutStoreId() )) {
                            transfer.setOutStoreId_dictText("线上商城");
                        }
                    }
                }
                if (oConvertUtils.isNotEmpty(transfer.getConfirmInSalesId())) {
                    if (salesMap.containsKey(transfer.getConfirmInSalesId())) {
                        transfer.setConfirmInSalesId_dictText(salesMap.get(transfer.getConfirmInSalesId()));
                    }
                }
                if (oConvertUtils.isNotEmpty(transfer.getConfirmOutSalesId())) {
                    if (salesMap.containsKey(transfer.getConfirmOutSalesId())) {
                        transfer.setConfirmOutSalesId_dictText(salesMap.get(transfer.getConfirmOutSalesId()));
                    }
                }
            });
        }
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param stmTransferPage
     * @return
     */
    @AutoLog(value = "门店调拨单-添加")
    @ApiOperation(value = "门店调拨单-添加", notes = "门店调拨单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody StmTransferPage stmTransferPage) {
        StmTransfer stmTransfer = new StmTransfer();
        BeanUtils.copyProperties(stmTransferPage, stmTransfer);
        stmTransfer.setStatus(0);
        stmTransferService.save(stmTransfer);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param stmTransferPage
     * @return
     */
    @AutoLog(value = "门店调拨单-编辑")
    @ApiOperation(value = "门店调拨单-", notes = "门店调拨单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody StmTransferPage stmTransferPage) {
        StmTransfer stmTransfer = new StmTransfer();
        BeanUtils.copyProperties(stmTransferPage, stmTransfer);
        stmTransferService.updateById(stmTransfer);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "门店调拨单-通过id删除")
    @ApiOperation(value = "门店调拨单-通过id删除", notes = "门店调拨单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) Long id) {
        stmTransferService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "门店调拨单-批量删除")
    @ApiOperation(value = "门店调拨单-批量删除", notes = "门店调拨单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.stmTransferService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "门店调拨单-通过id查询")
    @ApiOperation(value = "门店调拨单-通过id查询", notes = "门店调拨单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) Long id) {
        StmTransfer stmTransfer = stmTransferService.getById(id);
        return Result.ok(stmTransfer);
    }


    /**
     * 确认发货
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "门店调拨单-确认发货")
    @PostMapping(value = "/confirmBatchOut")
    public Result<?> confirmBatchOut(@RequestBody String[] ids) {
        LambdaQueryWrapper<StmTransfer> query = new LambdaQueryWrapper<>();
        query.in(StmTransfer::getId,ids);
        List<StmTransfer> transfers = stmTransferService.list(query);

        LambdaQueryWrapper<StmTransferItem> itemQuery = new LambdaQueryWrapper<>();
        itemQuery.in(StmTransferItem::getTransferId,ids);
        List<StmTransferItem> transferItems = stmTransferItemService.list(itemQuery);
        Map<Long, List<StmTransferItem>> itemMap = transferItems.stream().collect(Collectors.groupingBy(e -> e.getTransferId()));

        transfers.forEach(transfer -> {
            if(Arrays.asList(3).contains(transfer.getStatus())){
                if (itemMap.containsKey(transfer.getId())) {
                    List<StmTransferItem> items = itemMap.get(transfer.getId());
                    List<StmStockVO> stockVOList = new ArrayList<>();
                    List<StmTransferItem> updateItems = new ArrayList<>();
                    items.forEach(item->{
                        StmStockVO vo = new StmStockVO();
                        vo.setProductId(item.getProductId());
                        vo.setProductSn(item.getProductSn());
                        vo.setStockType(item.getStockType());
                        vo.setProductQty(item.getProductQty());
                        StmTransferItem updateItem = new StmTransferItem();
                        updateItem.setSendQty(item.getProductQty());
                        updateItem.setId(item.getId());
                        updateItems.add(updateItem);
                        stockVOList.add(vo);
                    });
                    String changeReason = "调拨出库";
                    stmStockService.stockInOut(stockVOList, transfer.getOutStoreId(), StockConstant.STOCK_OUT, StockConstant.STOCK_OUT_TYPE_TRANSFER, StockConstant.RECEIPT_TYPE_TRANSFER, transfer.getId().toString(), changeReason );
                    StmTransfer updateTransfer = new StmTransfer();
                    updateTransfer.setStatus(5);
                    updateTransfer.setId(transfer.getId());
                    updateTransfer.setStockOutTime(new Date());
                    stmTransferService.updateById(updateTransfer);
                    stmTransferItemService.updateBatchById(updateItems);
                    LambdaQueryWrapper<StmReplenishmentTransferRelation> relationQueryWrapper = new LambdaQueryWrapper<>();
                    relationQueryWrapper.eq(StmReplenishmentTransferRelation::getTransferId,  transfer.getId());
                    relationQueryWrapper.eq(StmReplenishmentTransferRelation::getCancelFlag, 0);
                    List<StmReplenishmentTransferRelation> relationList = stmReplenishmentTransferRelationService.list(relationQueryWrapper);
                    if (oConvertUtils.isNotEmpty(relationList) && relationList.size() > 0) {
                        List<Long> replenishmentIds = relationList.stream().map(e -> e.getReplenishmentId()).collect(Collectors.toList());
                        LambdaUpdateWrapper<StmReplenishment> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.set(StmReplenishment::getStatus, 5);
                        updateWrapper.in(StmReplenishment::getId, replenishmentIds);
                        stmReplenishmentService.update(updateWrapper);
                    }
                }
            }
        });


        return Result.ok("发货成功！");
    }

    /**
     * 确认收货
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "门店调拨单-确认收货")
    @PostMapping(value = "/confirmBatchIn")
    public Result<?> confirmBatchIn(@RequestBody String[] ids) {
        LambdaQueryWrapper<StmTransfer> query = new LambdaQueryWrapper<>();
        query.in(StmTransfer::getId,ids);
        List<StmTransfer> transfers = stmTransferService.list(query);

        LambdaQueryWrapper<StmTransferItem> itemQuery = new LambdaQueryWrapper<>();
        itemQuery.in(StmTransferItem::getTransferId,ids);
        List<StmTransferItem> transferItems = stmTransferItemService.list(itemQuery);
        Map<Long, List<StmTransferItem>> itemMap = transferItems.stream().collect(Collectors.groupingBy(e -> e.getTransferId()));

        transfers.forEach(transfer -> {
            if(Arrays.asList(5).contains(transfer.getStatus())){
                if (itemMap.containsKey(transfer.getId())) {
                    List<StmTransferItem> items = itemMap.get(transfer.getId());
                    List<StmStockVO> stockVOList = new ArrayList<>();
                    List<StmTransferItem> updateItems = new ArrayList<>();
                    items.forEach(item->{
                        StmStockVO vo = new StmStockVO();
                        vo.setProductId(item.getProductId());
                        vo.setProductSn(item.getProductSn());
                        vo.setStockType(item.getStockType());
                        vo.setProductQty(item.getProductQty());
                        StmTransferItem updateItem = new StmTransferItem();
                        updateItem.setReceiveQty(item.getProductQty());
                        updateItem.setId(item.getId());
                        updateItems.add(updateItem);
                        stockVOList.add(vo);
                    });
                    String changeReason = "调拨入库";
                    stmStockService.stockInOut(stockVOList, transfer.getInStoreId(), StockConstant.STOCK_IN, StockConstant.STOCK_IN_TYPE_TRANSFER, StockConstant.RECEIPT_TYPE_TRANSFER, transfer.getId().toString(), changeReason );
                    StmTransfer updateTransfer = new StmTransfer();
                    updateTransfer.setStatus(7);
                    updateTransfer.setStockInTime(new Date());
                    updateTransfer.setId(transfer.getId());
                    stmTransferService.updateById(updateTransfer);
                    stmTransferItemService.updateBatchById(updateItems);
                    LambdaQueryWrapper<StmReplenishmentTransferRelation> relationQueryWrapper = new LambdaQueryWrapper<>();
                    relationQueryWrapper.eq(StmReplenishmentTransferRelation::getTransferId,  transfer.getId());
                    relationQueryWrapper.eq(StmReplenishmentTransferRelation::getCancelFlag, 0);
                    List<StmReplenishmentTransferRelation> relationList = stmReplenishmentTransferRelationService.list(relationQueryWrapper);
                    if (oConvertUtils.isNotEmpty(relationList) && relationList.size() > 0) {
                        List<Long> replenishmentIds = relationList.stream().map(e -> e.getReplenishmentId()).collect(Collectors.toList());
                        LambdaUpdateWrapper<StmReplenishment> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.set(StmReplenishment::getStatus, 7);
                        updateWrapper.in(StmReplenishment::getId, replenishmentIds);
                        stmReplenishmentService.update(updateWrapper);
                    }
                }
            }
        });


        return Result.ok("收货成功！");
    }

    //===========================以下是子表信息操作相关API====================================

    /**
     * 通过主表id查询门店调拨单明细
     *
     * @param stmTransferItem
     * @return
     */
    @AutoLog(value = "门店调拨单明细-通过主表id查询")
    @ApiOperation(value = "门店调拨单明细-通过主表id查询", notes = "门店调拨单明细-通过主表id查询")
    @GetMapping(value = "/listStmTransferItemByMainId")
    public Result<?> listStmTransferItemByMainId(StmTransferItem stmTransferItem,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) {
        if (stmTransferItem.getTransferId() != null) {
            QueryWrapper<StmTransferItem> queryWrapper = QueryGenerator.initQueryWrapper(stmTransferItem, req.getParameterMap());
            Page<StmTransferItem> page = new Page<StmTransferItem>(pageNo, pageSize);
            //IPage<StmTransferItem> pageList = stmTransferItemService.getTransferItemProductPage(page, queryWrapper);
            IPage<StmTransferItem> pageList = stmTransferItemService.page(page, queryWrapper);
            return Result.ok(pageList);
        } else {
            return Result.error("请选择调拨记录");
        }
    }

    /**
     * 通过id查询
     *
     * @param mainId
     * @return
     */
    @AutoLog(value = "门店调拨单明细-通过MainId查询")
    @ApiOperation(value = "门店调拨单明细-通过MainId查询", notes = "门店调拨单明细-通过MainId查询")
    @GetMapping(value = "/queryTransferItemByMainId")
    public Result<?> queryTransferItemByMainId(@RequestParam(name = "mainId", required = true) String mainId) {
        log.info("mainId：" + mainId);
        StmTransfer stmTransfer = stmTransferService.getById(Long.valueOf(mainId));
        List<StmPrintVO> stmTransferPrintList = stmTransferItemService.getTransferItemForPrint(Long.valueOf(mainId),stmTransfer.getCreateTime());
        return Result.ok(stmTransferPrintList);
    }

    /**
     * 添加门店调拨单明细
     *
     * @param stmTransferItemModel
     * @return
     */
    @AutoLog(value = "门店调拨单明细-添加")
    @ApiOperation(value = "门店调拨单明细-添加", notes = "门店调拨单明细-添加")
    @PostMapping(value = "/addStmTransferItem")
    public Result<?> addStmTransferItem(@RequestBody StmTransferItemModel stmTransferItemModel) {
        if (oConvertUtils.isEmpty(stmTransferItemModel) || oConvertUtils.isEmpty(stmTransferItemModel.getTransferId()) || oConvertUtils.isEmpty(stmTransferItemModel.getDetailList())) {
            return Result.error("数据为空！");
        }
        StmTransfer stmTransfer = stmTransferService.getById(stmTransferItemModel.getTransferId());
        if (oConvertUtils.isEmpty(stmTransfer)) {
            return Result.error("调拨单主表记录为空，请检查后重试！");
        }
        if (stmTransfer.getStatus() > 0) {
            return Result.error("该调拨单不是初始状态，不可再增加商品！");
        }
        List<String> productSns = stmTransferItemModel.getDetailList().stream().map(StmTransferItem::getProductSn).collect(Collectors.toList());
        long count = productSns.stream().distinct().count();
        if (count < productSns.size()) {
            return Result.error("新添加的记录中存在重复数据，请重核对后重试！");
        }
        LambdaQueryWrapper<PmsProduct> query = new LambdaQueryWrapper<>();
        query.in(PmsProduct::getProductSn, productSns);
        List<PmsProduct> products = pmsProductService.list(query);
        Map<String, Long> productMaps = products.stream().collect(Collectors.toMap(PmsProduct::getProductSn, PmsProduct::getId, (key1, key2) -> key2));
        List<StmTransferItem> stmTransferItemList = stmTransferItemService.selectByMainId(stmTransferItemModel.getTransferId());
        if (oConvertUtils.isNotEmpty(stmTransferItemList) && stmTransferItemList.size() > 0) {
            List<Long> productIds =  products.stream().map(PmsProduct::getId).collect(Collectors.toList());
            List<Long> dbItemProductIds = stmTransferItemList.stream().map(StmTransferItem::getProductId).collect(Collectors.toList());
            List<Long> mixes = productIds.stream().filter(r->dbItemProductIds.contains(r)).collect(Collectors.toList());
            if (oConvertUtils.isNotEmpty(mixes) && mixes.size() > 0) {
                return Result.error("新添加的记录已存在，请重核对后重试！");
            }
        }
        stmTransferItemModel.getDetailList().forEach(r->{
            r.setTransferId(stmTransferItemModel.getTransferId());
            r.setProductId(productMaps.get(r.getProductSn()));
        });
        stmTransferItemService.saveBatch(stmTransferItemModel.getDetailList());
        return Result.ok("添加门店调拨单明细成功！");
    }

    /**
     * 编辑门店调拨单明细
     *
     * @param stmTransferItem
     * @return
     */
    @AutoLog(value = "门店调拨单明细-编辑")
    @ApiOperation(value = "门店调拨单明细-编辑", notes = "门店调拨单明细-编辑")
    @PutMapping("/editStmTransferItem")
    public Result<?> editStmTransferItem(@RequestBody StmTransferItem stmTransferItem) {
        StmTransfer stmTransfer = stmTransferService.getById(stmTransferItem.getTransferId());
        if (oConvertUtils.isEmpty(stmTransfer)) {
            return Result.error("调拨单不存在，请检查后重试！");
        }
        if (stmTransfer.getStatus() > 0) {
            return Result.error("该调拨单不是初始状态，不可再增加商品！");
        }
        stmTransferItemService.updateById(stmTransferItem);
        return Result.ok("编辑门店调拨单明细成功！");
    }

    /**
     * 通过id删除门店调拨单明细
     *
     * @param id
     * @return
     */
    @AutoLog(value = "门店调拨单明细-通过id删除")
    @ApiOperation(value = "门店调拨单明细-通过id删除", notes = "门店调拨单明细-通过id删除")
    @DeleteMapping(value = "/deleteStmTransferItem")
    public Result<?> deleteStmTransferItem(@RequestParam(name = "id", required = true) Long id) {
        StmTransferItem transferItem = stmTransferItemService.getById(id);
        StmTransfer stmTransfer = stmTransferService.getById(transferItem.getTransferId());
        if (oConvertUtils.isEmpty(stmTransfer)) {
            return Result.error("调拨单不存在，请检查后重试！");
        }
        if (stmTransfer.getStatus() > 0) {
            return Result.error("该调拨单不是初始状态，不可再增加商品！");
        }
        stmTransferItemService.removeById(id);
        return Result.ok("删除门店调拨单明细成功！");
    }

    /**
     * 批量删除门店调拨单明细
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "门店调拨单明细-批量删除")
    @ApiOperation(value = "门店调拨单明细-批量删除", notes = "门店调拨单明细-批量删除")
    @DeleteMapping(value = "/deleteBatchStmTransferItem")
    public Result<?> deleteBatchStmTransferItem(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        }
        this.stmTransferItemService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");

    }


    /**
     * 导出excel
     *
     * @param request
     * @param stmTransfer
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StmTransfer stmTransfer) {
        // Step.1 组装查询条件
        QueryWrapper<StmTransfer> queryWrapper = QueryGenerator.initQueryWrapper(stmTransfer, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //要么导出选中的，要么空
        String selections = request.getParameter("selections");
        if (oConvertUtils.isEmpty(selections)) {
            return null;
        }
        List<Long> selectionList = Arrays.asList(selections.split(",")).stream().map(s -> Long.valueOf(s.toString())).collect(Collectors.toList());
        queryWrapper.in("id", selectionList);

        //Step.2 获取导出数据
        //List<StmTransferPage> pageList = new ArrayList<StmTransferPage>();
        List<StmTransfer> stmTransferList = stmTransferService.list(queryWrapper);
        StmTransfer maxTransfer = stmTransferList.stream().max(Comparator.comparing(StmTransfer::getCreateTime)).get();
        Date createTime = maxTransfer.getCreateTime();

        List<StmPrintVO> pageList = stmTransferService.selectByIds(selectionList,createTime);

        String storeName = "";

        //Step.3 调用AutoPoi导出Excel
        ModelAndView mv = new ModelAndView(new EntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "门店调拨单");
        mv.addObject(NormalExcelConstants.CLASS, StmPrintVO.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(storeName+"调拨单数据", "导出人:" + sysUser.getRealname(), storeName+"调拨单"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);

        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<StmTransferPage> list = ExcelImportUtil.importExcel(file.getInputStream(), StmTransferPage.class, params);
                for (StmTransferPage page : list) {
                    StmTransfer po = new StmTransfer();
                    BeanUtils.copyProperties(page, po);
                    stmTransferService.saveMain(po, page.getStmTransferItemList());
                }
                return Result.ok("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }
}
